import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:industry_net/base/common/util.dart';
import 'package:industry_net/pages/msg/main/state.dart';
import 'package:industry_net/pages/msg/models/msg.dart';

class MsgController extends GetxController
    with GetSingleTickerProviderStateMixin {
  final state = MsgState();
  late TabController tabCtrl;
  @override
  void onInit() {
    super.onInit();
    tabCtrl = TabController(length: 2, vsync: this)
      ..addListener(() {
        if (tabCtrl.indexIsChanging) {
          if (tabCtrl.previousIndex != tabCtrl.index) {
            state.tabIndex.value = tabCtrl.index;
          }
        }
      });
  }

  @override
  onReady() {
    getData().then((value) {
      state.dataSource = value ?? [];
      update();
    });

    super.onReady();
  }

  Future<List<MsgModel>?> getData() async {
    return List.generate(20, (index) => MsgModel());
  }

  void onRefresh() async {
    state.pageIndex = 1;
    await Future.delayed(Duration(
      seconds: 2,
    ));
    var _list = await getData();
    state.dataSource = _list ?? [];
    if (state.refreshCtrl.isRefresh) {
      if (_list == null) {
        state.refreshCtrl.refreshFailed();
      } else if (_list.isEmpty) {
        state.refreshCtrl.refreshToIdle();
      } else {
        state.refreshCtrl.refreshCompleted();
      }
    }
    update();
  }

  void onLoading() async {
    state.pageIndex += 1;
    var _list = await getData();
    state.dataSource.addAll(_list ?? []);
    if (state.refreshCtrl.isRefresh) {
      if (_list == null) {
        state.refreshCtrl.loadFailed();
      } else if (_list.isEmpty) {
        state.refreshCtrl.loadNoData();
      } else {
        state.refreshCtrl.loadComplete();
      }
    }
    update();
  }

  void actionCellClick(MsgModel md) {
    // Get.toNamed(RouterPath.map_earth);
    Get.toNamed(RouterPath.logistics_list);
    // Get.to(() => PolygonDemoPage('title', 'subTitle'));
  }

  void actionClear() {
    if (state.tabIndex.value != 0) {
      return;
    }
    state.dataSource = [];
    update();
  }

  void actionDel(MsgModel md) {
    state.dataSource.remove(md);
    update();
  }

  void actionTop(MsgModel md) {
    md.isTop = true;
    state.dataSource.remove(md);
    state.dataSource.insert(0, md);
    update();
  }

  void actionRead(MsgModel md) {
    md.isRead = true;
    update();
  }
}
